package com.youlu.campus.monitor.service.impl;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.monitor.entity.WechatQuestion;
import com.youlu.campus.monitor.entity.WechatQuestionPageQuery;
import com.youlu.campus.monitor.repositories.WechatQuestionRepository;
import com.youlu.campus.monitor.service.WechatMonitorService;
import com.youlu.campus.monitor.service.WechatQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 微信监控任务业务逻辑实现类
 * 处理业务校验、异常抛出，返回业务对象，不封装QResult
 *
 * @author su
 * @date 2025/09/02
 */
@Service
@Slf4j
public class WechatQuestionServiceImpl implements WechatQuestionService {

    @Resource
    private WechatQuestionRepository questionRepository;

    @Resource
    private MongoTemplate wechatMonitorMongoTemplate;

    @Autowired
    private WechatMonitorService wechatMonitorService;

    @Override
    public WechatQuestion save(WechatQuestion question) {
        Assert.hasText(question.getMonitorId(), "监控任务id不能为空");
        Assert.hasText(question.getQuestion(), "问题不能为空");
        Assert.hasText(question.getAnswer(), "答案不能为空");
        // 新增任务（MongoDB自动生成id）
        if (StringUtils.isBlank(question.getId())) {
            question.setCreateTime(LocalDateTime.now());
        } else {
            Optional<WechatQuestion> questionOpt = questionRepository.findById(question.getId());
            if (!questionOpt.isPresent()) {
                throw new BusinessException("数据不存在");
            }
            question.setCreateTime(questionOpt.get().getCreateTime());
            question.setUpdateTime(LocalDateTime.now());
        }
        question = questionRepository.save(question);
        log.info("新增微信监控任务成功，任务id：{}，任务名称：{}", question.getId(), question.getQuestion());
        return question;
    }

    @Override
    public boolean deleteById(String id) {
        // 参数校验
        Assert.hasText(id, "id不能为空");
        // 执行删除
        questionRepository.deleteById(id);
        return true;
    }

    @Override
    public WechatQuestion findById(String id) {
        // 参数校验
        Assert.hasText(id, "任务id不能为空");
        Optional<WechatQuestion> taskOpt = questionRepository.findById(id);
        log.info("查询微信监控任务详情成功，任务id：{}", id);
        return taskOpt.orElse(null);
    }

    @Override
    public Page<WechatQuestion> findByPage(WechatQuestionPageQuery pageQuery) {
        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getQuestion())) {
            query.addCriteria(Criteria.where("question").regex(pageQuery.getQuestion(), "i"));
        }
        if (StringUtils.isNotBlank(pageQuery.getMonitorId())) {
            query.addCriteria(Criteria.where("monitorId").is(pageQuery.getMonitorId()));
        }
        //统计总条数（分页需要先查总数）
        long total = wechatMonitorMongoTemplate.count(query, WechatQuestion.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("createTime").descending());
        List<WechatQuestion> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = wechatMonitorMongoTemplate.find(query, WechatQuestion.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }


    @Override
    public void deleteByMonitorId(String id) {
        // 删除任务
        questionRepository.deleteByMonitorId(id);
    }
}
    